//
//  MBHomeViewController.m
//  MemberBusiness-ios
//
//  Created by cherry pu on 2018/4/18.
//  Copyright © 2018年 zhangXin. All rights reserved.
//

#import "MBHomeViewController.h"
#import "MBMessageViewController.h"
#import "MBScanViewController.h"
#import "MBHomeMessageView.h"
#import "MBHomeHeaderView.h"
#import "MBLoginViewController.h"
#import "AppDelegate.h"
#import "MBMessageViewModel.h"
#import <UMPush/UMessage.h>
#import "MBScanNumPopView.h"

@interface MBHomeViewController ()
@property (nonatomic,weak)UIScrollView* scrollView;

@end

@implementation MBHomeViewController
@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupLayout];
}

-(void)setupLayout
{
    [super setupLayout];
        
    self.view.backgroundColor = COLOR_BG;
    
    self.naviView.titleLabel.text = @"首页";
    UIButton* rightButton = [[UIButton alloc]init];
    [rightButton addTarget:self action:@selector(handleClickRightItem) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setImage:[UIImage imageNamed:@"nav_message"] forState:UIControlStateNormal];
    [self.naviView addSubview:rightButton];
    
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.naviView.titleLabel);
        make.right.equalTo(self.naviView).offset([UIView lf_sizeFromIphone6:-13]);
    }];

    MBHomeHeaderView* headerView = [[MBHomeHeaderView alloc]init];
    [self.view addSubview:headerView];
    
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(SCREEN_STATUS_BAR_HEIGHT+44);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo([UIView lf_sizeFromIphone6:69]);
    }];
    
    [headerView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleClickHeaderView)]];
    
    UIScrollView* scrollView = [[UIScrollView alloc]init];
    self.scrollView = scrollView;
    [self.view addSubview:scrollView];
    
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    @weakify(self);
    // 添加头部刷新控件
    MJRefreshNormalHeader * activityHeader = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self setUpData];
    }];
    scrollView.mj_header = activityHeader;
    [activityHeader setTitle:@"下拉即可刷新" forState:MJRefreshStateIdle];
    [activityHeader setTitle:@"松开即可更新" forState:MJRefreshStatePulling];
    [activityHeader setTitle:@"加载中" forState:MJRefreshStateRefreshing];
    activityHeader.lastUpdatedTimeLabel.hidden = YES;

    
    MBHomeMessageView* message1 = [[MBHomeMessageView alloc]init];
    message1.viewModel = self.viewModel;
    [scrollView addSubview:message1];
    
    [message1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(scrollView).offset([UIView lf_sizeFromIphone6:10]);
        make.left.equalTo(scrollView).offset([UIView lf_sizeFromIphone6:5]);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-[UIView lf_sizeFromIphone6:10], [UIView lf_sizeFromIphone6:340]));
    }];
    
    
    MBHomeMessageView* message2 = [[MBHomeMessageView alloc]init];
    message2.viewModel = self.viewModel;
    message2.titleLabel.text = @"历史统计";
    [scrollView addSubview:message2];
    
    [message2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(message1.mas_bottom);
        make.left.equalTo(scrollView).offset([UIView lf_sizeFromIphone6:5]);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-[UIView lf_sizeFromIphone6:10], [UIView lf_sizeFromIphone6:340]));
        make.bottom.right.equalTo(scrollView);
    }];

    [scrollView.mj_header beginRefreshing];
    
    [RACObserve(self.viewModel, isNeedUpdate) subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        if (self.viewModel.isNeedUpdate) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"《梦巴士商户端》有新版本啦，是否前往更新？" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSString *itunesurl = @"itms-apps://itunes.apple.com/cn/app/id1380693804?mt=8";
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:itunesurl]];
            }]];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:nil]];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
    
    [[headerView.scanNumButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        MBScanNumPopView* popView = [[MBScanNumPopView alloc]init];
        [popView show];
    }];
    
    [[headerView.scanButton rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        MBScanViewModel* viewModel = [[MBScanViewModel alloc]init];
        MBScanViewController* scanVC = [[MBScanViewController alloc]initWithViewModel:viewModel];
        [self.navigationController pushViewController:scanVC animated:YES];
    }];
}

-(void)setUpData
{
    [self.viewModel sendRequest:^(bool success) {
        [self.scrollView.mj_header endRefreshing];
    }];
}

-(void)handleClickHeaderView
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认退出当前账号吗？" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MBLoginUserModel* userModel = [MBLoginUserModelArchieveTool userInfoUnAchieveFromFile];
        [UMessage removeAlias:[NSString stringWithFormat:@"%ld",(long)userModel.user_id] type:[NSString stringWithFormat:@"%ld",(long)userModel.user_id] response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
            
        }];
        [MBLoginUserModelArchieveTool removeSelfUserFromDisk];
        
        MBLoginViewModel* viewModel = [[MBLoginViewModel alloc]init];
        MBLoginViewController* loginVC = [[MBLoginViewController alloc]initWithViewModel:viewModel];
        AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        appDelegate.window.rootViewController = loginVC;
        [appDelegate.window makeKeyWindow];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)handleClickRightItem
{
    MBMessageViewController* messageVC = [[MBMessageViewController alloc]initWithViewModel:[[MBMessageViewModel alloc]init]];
    [self.navigationController pushViewController:messageVC animated:YES];
}

@end
